<?php

declare(strict_types=1);

namespace EthanZ\HyperfExt\Controller;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\HttpServer\Router\Dispatched;
use Hyperf\Utils\Str;
use Psr\Container\ContainerInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Container\ContainerExceptionInterface;

abstract class BaseController
{


    #[Inject]
    protected ContainerInterface $container;

    #[Inject]
    protected RequestInterface   $request;

    #[Inject]
    protected ResponseInterface  $response;


    public function __construct()
    {
        // 通用验证.
//        $this->commonValidate();
    }


    /**
     * 通用验证
     *
     * @throws ContainerExceptionInterface|NotFoundExceptionInterface
     */
    protected function commonValidate()
    {
        // 获取path信息.
        $action = $this->request->getAttribute(Dispatched::class)->handler->callback;
        // 截取className和actionName.
        list($class, $currentScene) = explode('@', $action);
        $class = Str::between($class, 'App\Controller\\', 'Controller');
        // 拼接验证类名.
        $requestName = "App\Request\\{$class}Request";
        // 检查验证类是否存在.
        if (Class_exists($requestName)) {
            // 进行验证.
            $this->request = $this->container->get($requestName);
            $this->request->validateResolved();
        }
    }
}
